<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2018/7/13
 * Time: 17:24
 */
namespace app\wchat\controller;
use app\repository\code\Code;
use app\repository\wechat\Wechat;
use think\App;
use think\captcha\Captcha;
use think\Controller;
use think\Request;

class Binding extends Controller
{
    /**
     * 绑定页面
     * @return mixed
     */
    public function index(){

        if(!session('openid')){
            $info = (new Wechat())->W();
            session('openid',$info['openid']);
        }

        $c = db('admin')->where('openid',session('openid'))->find();

        if($c)
            return "<div style='color: green;font-size: 55px;text-align: center;line-height: 450px;'>你已绑定账户：".$c['username']."</div>";
        return $this->fetch('index',['openid'=>session('openid')]);
    }

    /**
     * 绑定提交
     * @param Request $request
     */
    public function bind(Request $request){
        $u = $request->param('username');
        $p = $request->param('pass');

        $code = $request->param('code');

        $openid = $request->param('openid');

        if(empty($openid)) return ['code'=>0,'msg'=>'获取用户openID参数错误'];

        $bl = $this->verif($code);

        if($bl != true){
            $this->error("验证码错误");
        }

        if(empty($u)) return ['code'=>0,'msg'=>'用户名不能为空'];
        if(empty($p)) return ['code'=>0,'msg'=>'密码不能为空'];

        $row = db('admin')->where('username',$u)->find();

        if($row){

            if(!in_array($row['group_id'],[5,7,9,10])){
                return ['code'=>0,'msg'=>'绑定角色有误'];
            }

            if(md5($p) == $row['pwd']){
                db('admin')->where('openid',$openid)->update(['openid'=>0]);
                db('admin')->where('admin_id',$row['admin_id'])->update(['openid'=>$openid]);

                return ['code'=>1,'msg'=>'绑定成功'];

            }
        }

        return ['code'=>0,'msg'=>'用户名或密码错误'];
    }

    /**
     * 解除绑定
     */
    public function remove(){
        $info = (new Wechat())->W();
        $row = db('admin')->where('openid',$info['openid'])->update(['openid'=>'0']);
        session('muid',null);
        session('mgid',null);
        session_destroy();
        return $this->fetch('remove',['row'=>$row]);
    }


    private function verif($code){
        return (new Code())->check($code);
    }
}